﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MRS.FrontEnd.BO;

namespace Microsoft.Reputation.Services
{
    public class DPLookupResponse
    {
        public List<UnpackedObject> Matches { get; set; }

        /// <summary>
        /// Convert the array of DPLookupResponses that were built by lower layers
        /// into LookupResponse objects that can be returned to calling clients
        /// </summary>
        /// <param name="dpResponses">Responses from the lower layers</param>
        /// <param name="requests">The LookupRequests from the calling client that 
        /// were converted and retrieved from the database</param>
        /// <returns>The LookupResponses to return to the calling client</returns>
        internal static List<LookupResponse> ConvertLookupToLookupResponses(
            DPLookupResponse[] dpResponses,
            LookupRequest[] requests)
        {
            List<LookupResponse> responses = new List<LookupResponse>(requests.Length);
            for (int i = 0; i < requests.Length; i++)
            {
                DPLookupResponse dpResponse = dpResponses[i];

                responses.Add(dpResponse.GetLookupResponse(
                    requests[i],
                    requests[i].OverrideRequest == false ? (uint)i : DeliveryServiceConfig.OverrideResponseSequenceNumber
                    ));
            }

            return responses;
        }

        /// <summary>
        /// Convert the DPLookupResponse (this) into a LookupResponse
        /// </summary>
        /// <param name="request">The LookupRequest that was used to create this DPLookupResponse</param>
        /// <param name="sequenceNumber">The sequence number that will be used for the LookupResponse</param>
        /// <returns>A LookupResponse that can be returned to the calling client</returns>
        private LookupResponse GetLookupResponse(
            LookupRequest request,
            uint sequenceNumber)
        {
            List<ReputationObject> repuObjectMatches = new List<ReputationObject>(
                this.Matches.Select(m => ReputationObject.ConvertUnpackedObjectToReputationObject(m))
                );

            LookupResponse response = new LookupResponse(
                StatusCodes.OK,
                sequenceNumber,
                null,
                repuObjectMatches);

            return response;
        }
    }
}
